#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Implements register request command

    :copyright: (c) 2014 by Duxin.
'''

import cgi
import Cookie
import os
import hashlib

import command
import app
import sessions
from db.db_manager import UserDAO, User
from exception import ParameterError

class Register(command.Command):
    '''
        registers for new user. checks whether username is valid.
        stores the MD5 value of password.
        this command is publicly accessible.
    '''
    
    def is_param_right(self):  
        self.username = self.get_param('username')
        if self.username == None:
            raise ParameterError('error_用户名不能为空')
        
        self.password = self.get_param('password')
        if self.password == None:
            raise ParameterError('error_密码不能为空')

    def execute(self):
        user = UserDAO.find_by_username(self.username)
        
        if user:
            return "error_用户名已被使用"
        else:
            p = re.compile("^[a-zA-Z0-9_]{3,16}$")
            
            if not p.match(self.username):
                return "error_用户名不合法"
            
            user = User()
            user.username = self.username
            user.password = hashlib.md5(self.password).hexdigest()
            
            if UserDAO.persist(user):
                session = self.get_session()
                session.set_attribute('user',  user)
                return "success"
            else:
                return "error_数据写入失败"

app.App.start(Register())
